package com.mysiteforme.admin.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.mysiteforme.admin.config.SysMetaObjectHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jayden
 */
@EnableTransactionManagement
@Configuration
//@Primary
//,sqlSessionFactoryRef = "sqlSessionFactory"
@MapperScan(basePackages ="com.mysiteforme.admin.dao")
public class MybatisPlusConfig {


    @Value("${mybatis-plus.mapper-locations}")
    private String mapperLocations;
    @Value("${mybatis-plus.typeAliasesPackage}")
    private String typeAliasesPackage;

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLocalPage(true);
        paginationInterceptor.setDialectType("mysql");
        return paginationInterceptor;
    }

    @Bean(name = "db_backend")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db_backend")
    public DataSource db_backend() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "db_user")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db_user")
    public DataSource db_user() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "db_course")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db_course")
    public DataSource db_course() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "db_question")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db_question")
    public DataSource db_question() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "db_base")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db_base")
    public DataSource db_base() {
        return DruidDataSourceBuilder.create().build();
    }


    @Bean
    public PlatformTransactionManager txManager(DataSource multipleDataSource) {
        return new DataSourceTransactionManager(multipleDataSource);
    }
    /**
     * 动态数据源配置
     *
     * @return
     */
    @Bean(name = "multipleDataSource")
    @Primary
    public DynamicDataSource multipleDataSource(@Qualifier("db_backend") DataSource db_backend,
                                         @Qualifier("db_user") DataSource db_user,
                                         @Qualifier("db_course") DataSource db_course,
                                                @Qualifier("db_question") DataSource db_question,
                                                @Qualifier("db_base") DataSource db_base

    ){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>(4);
        targetDataSources.put(DBTypeEnum.db_backend.getValue(), db_backend);
        targetDataSources.put(DBTypeEnum.db_user.getValue(), db_user);
        targetDataSources.put(DBTypeEnum.db_course.getValue(), db_course);
        targetDataSources.put(DBTypeEnum.db_question.getValue(), db_question);
        targetDataSources.put(DBTypeEnum.db_base.getValue(), db_base);
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(db_backend);
        return dynamicDataSource;
    }

    @Bean("sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("multipleDataSource")  DataSource multipleDataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(multipleDataSource);
        sqlSessionFactory.setTypeAliasesPackage(typeAliasesPackage);
        sqlSessionFactory
                .setMapperLocations(new PathMatchingResourcePatternResolver()
                        .getResources(mapperLocations));
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        sqlSessionFactory.setConfiguration(configuration);
        //PerformanceInterceptor(),OptimisticLockerInterceptor()
        //添加分页功能
        sqlSessionFactory.setPlugins(new Interceptor[]{
                paginationInterceptor()
        });
//        sqlSessionFactory.setGlobalConfig(globalConfiguration());
        return sqlSessionFactory.getObject();
    }

    @Bean
    public GlobalConfiguration globalConfiguration() {
        GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
        conf.setLogicDeleteValue("-1");
        conf.setLogicNotDeleteValue("1");
        conf.setIdType(0);
        conf.setFieldStrategy(2);
        conf.setMetaObjectHandler(new SysMetaObjectHandler());
        conf.setDbColumnUnderline(true);
        conf.setRefresh(true);
        return conf;
    }

    @Bean
    public MybatisConfiguration mybatisConfiguration() {
        MybatisConfiguration conf = new MybatisConfiguration();
        conf.setMapUnderscoreToCamelCase(true);
        conf.setCacheEnabled(false);
        return conf;
    }
}
